<?php
namespace Home\Model;
use Think\Model\AdvModel;
/**
 * 会员表模型
 */
class UserMemberModel extends AdvModel{
	public function __construct(){
		parent::__construct();
	}
	/**
	 * [addUserMember description]添加会员的方法
	 * @param [type] $post [description]表单接收到的值
	 */
	public function addUserMember($post){
		$arr['password'] 	 = MD5($post['password']);
		//截取帐号前俩位继续加密
		$str = substr($post['mobile'],9,11);
		//最终的加密密码
		$post['password']    = MD5($arr['password'].$str);
		unset($post['topassword']);
		unset($post['con']);
		unset($post['check']);
		$post['create_time'] = time();
		$post['mobile']      = $post['mobile'];
		$post['username']    = $post['mobile'];
		$post['update_time'] = time();
		// $this ->create($post);
		return $this ->add($post);
	}
	/**
	 * [showOne description]查找手机号看用户是否存在
	 * @param  [type] $post [description] 表单数据
	 * @return [type]       [description]
	 */
	public function showOne($post){
		$mobile = $post['mobile'];
		return $this ->where(array('username'=>$mobile,'status' =>1))->find();
	}
	/**
	 * [contrastPwd description]接收表单提交的密码进行比对
	 * @param  [type] $post [description]
	 * @return [type]       [description]
	 */
	public function contrastPwd($post){
		$mobile		 = $post['mobile'];
		$pwd 		 = MD5($post['password']);
		$str         = substr($post['mobile'],9,11);
		$password    = MD5($pwd.$str);
		return $this -> where(array('password'=>$password,'username' =>$mobile))->find();
	}
	public function showUser($id){
		return $this ->where(array('id' =>$id)) ->find();
	}
	public function updatePost($post){
		$id   = $post['id'];
		$post['update_time'] = time();
		unset($post['pid'],$post['end_top']);
		
		$data = $this ->create($post);
		return $this ->where(array('id' =>$id)) ->save($data);
	}
	/**
	 * 想教想学列表
	 * @param  int $teaching [教2，学1]
	 * @param  int $label    [课程标签]
	 * @param  int $sex      [性别]
	 * @param  int $age      [年龄]
	 * @param  int $identity [身份]
	 * @param  int $area_id  [地区]
	 * @param  int $star     [评价排序]
	 * @param  int $time     [发布时间排序]
	 * @param  int $salary   [最低课程价格排序]
	 * @param  str $keywords [搜索关键词]
	 * @return array         [用户列表]
	 * @author qlj
	 */
	public function userList($teaching, $label='', $sex='', $age='',$identity='',$area_id='', $star='', $time='', $salary='', $keywords='',$limit='',$limitrow='',$num){
		//教或学
        $mainfield = 'u.id,u.nickname,u.logo,u.sex,u.age,u.area_id,u.vip_endtime,u.lat,u.lng';
		$where['c.teaching'] = $map['teaching'] = $teaching;
		//如果是教师
		$map['passed'] = 1;
		if (!empty($label)) {
			//课程标签,用于构建子查询，查找有所选课程标签课程的uid
			$map['label'] = $label;
		}
		if (!empty($sex)) {
			//性别
			$where['u.sex'] = $sex;
		}
		if (!empty($age)) {
			//年龄
			if (strlen($age) == 2) {
				$where['u.age'] = array('gt', $age);
			} else if (strlen($age) == 5) {
				$where['u.age'] = array('between', $age);
			}
		}
		if (!empty($identity)) {
			//身份标识
			$where['u.identity'] = $identity;
		}
		if (!empty($area_id)) {
			//地区id
			$where['u.area_id'] = is_array($area_id) ? array('in',$area_id) : $area_id;
		}
		if (!empty($star)) {
			//按星级排序
			if ($star == 1) {
				$star = 'e.star desc';
			} else if ($star == 2) {
				$star = 'e.star';
			}
		}
		//子查询的字段
		$field = 'uid,teaching';
		if (!empty($time)) {
			//按时间排序course表
			if ($time == 1) {
				$c_order = 'create_time desc';
			} else if ($time == 2) {
				$c_order = 'create_time';
			}
			$field = 'uid,teaching,max(create_time) as create_time';
			//构建发布时间排序条件
			$time = 'c.' . $c_order;
		}
		if (!empty($salary)) {
            $mainfield .= ',c.salary';
			//按价格排序course表
			if ($salary == 1) {
				$c_order = 'salary asc';
			} else if ($salary == 2) {
				$c_order = 'salary desc';
			}
			$field = 'uid,teaching,min(salary) as salary';
			//构建价格排序条件
			$salary = 'c.' . $c_order;
		}
		//关键词搜索设置
		if (!empty($keywords) && $keywords != 'c' && $keywords != 'n') {
			$str = mb_substr($keywords,-1,1,'UTF8');
			$keywords = mb_substr($keywords, 0, -1, 'UTF8');
			if ($str == 'c') {
				$map['title'] = array('like', "%$keywords%");
			} elseif ($str == 'n') {
				$where['u.nickname'] = array('like', "%$keywords%");
			}
		}
		$map['status'] = 1;
		//子查询sql语句
		$course_uid = M('course') -> field($field) -> where($map) -> order($c_order) -> group('uid') -> select(false);
		//查询老师
		if ($teaching == 2) {
            $mainfield .= ',u.students';
			$where['u.end_teach'] = 0;
			//排序条件
			$order = $star.''.$time.''.$salary;
            if($num == 1){
                $a =  $this  ->alias('u') -> field('u.id,u.nickname,u.logo,u.sex,u.age,u.area_id,u.students') -> join('tutor_teacher_eva as e on u.id=e.uid') -> join("$course_uid as c on u.id=c.uid") -> where($where) -> order($order)  -> count();
                return $a;
            }else{
				$a = $this -> alias('u') -> field($mainfield) -> join('tutor_teacher_eva as e on u.id=e.uid') -> join("$course_uid as c on u.id=c.uid") -> where($where)-> order($order) -> select();
				
			/*数据按距离排序start yjmp*/
			$crt_lat = $_COOKIE['lat'];
			$crt_lng = $_COOKIE['lng'];
			if ($crt_lat) {
				$yj_uid = session('uid');
				if ($yj_uid) {
					$user_info = $this->where(array('id'=>$yj_uid))->find();
					$data['lat'] = $crt_lat;
					$data['lng'] = $crt_lng;
					$res = $this->where(array('id'=>$yj_uid))->save($data);	
				}
				//var_dump($user_info);exit;
				foreach ($a as $k => $v) {
					$lat = $a[$k]['lat'];
					$lng = $a[$k]['lng'];
					$a[$k]['distance'] = $this->get_distance($crt_lat,$crt_lng,$lat,$lng);
					$a[$k]['dis_show'] = $this->get_dis_show($a[$k]['distance']);
				}
			}
			if ($star == '' && $time == '' && $salary == ''&& $crt_lat) {
				$a = $this->array_sort($a, 'distance', $order=SORT_ASC);
			}
			
			$res = array_slice($a,$limit,$limitrow,false);
			/*数据按距离排序end yjmp*/
            return $res;
            }
		//查询学生
		} else if ($teaching == 1){
			$where['u.end_study'] = 0;
            if($num == 1){
                $a = $this -> alias('u') -> field('u.id,u.nickname,u.logo,u.sex,u.age,u.area_id,u.students') -> join('tutor_teacher_eva as e on u.id=e.uid') -> join("$course_uid as c on u.id=c.uid") -> where($where) -> order($order)  -> count();
                return $a;
            }else{
				$a = $this -> alias('u') -> field($mainfield) -> join("$course_uid as c on u.id=c.uid") -> where($where) -> order($order) -> select();
				/*数据按距离排序start yjmp*/
				$crt_lat = $_COOKIE['lat'];
				$crt_lng = $_COOKIE['lng'];
				if ($crt_lat){
					foreach ($a as $k => $v) {
						$lat = $a[$k]['lat'];
						$lng = $a[$k]['lng'];
						$a[$k]['distance'] = $this->get_distance($crt_lat,$crt_lng,$lat,$lng);
						$a[$k]['dis_show'] = $this->get_dis_show($a[$k]['distance']);
					}
				}
				if ($star == '' && $time == '' && $salary == ''&& $crt_lat) {
					$a = $this->array_sort($a, 'distance', $order=SORT_ASC);
				}
				/*数据按距离排序end yjmp*/
				$res = array_slice($a,$limit,$limitrow,false);
				return $res;
			}
        }
	}
	/**
	 * 查找自己所在的省和市
	 * @param  [type] $pid [description]
	 * @return [type]      [description]
	 */
	public function towArea($pid,$num = ''){
		$data = M('Area') ->field('id,title,pid') ->where(array('id' =>$pid)) ->find();
		$area = M('Area') ->field('id,title') ->where(array('id' =>$data['pid'])) ->find();
		$data['ar_title'] = $area['title'];
                if($num == 2){
                    $data = D('Area') ->field('pid') ->where(array('id' =>$pid)) ->find();
                    $areas = D('Area') ->field('id,title') ->where(array('pid' =>$data['pid'])) ->select();
                    return $areas;
                }
		return $data;
	}
	/* 检查看手机号码注册过没有 */
	public function showMobile($mobile){
		return $this ->where(array('username' =>$mobile)) ->find();
	}
	/**
	 * 检查用户密码对不对
	 */
	public function showPwd($password){
		//最终的加密密码
		$id = session('uid');
		$password = $this ->getMd5($id,$password,1);
		return $this ->where(array('id'=>$id,'password'=>$password))->find();
	}
	/**
	 * 修改密码
	 */
	public function updatePwd($password){
		$id = session('uid');
		$password = MD5($password);
		$password = MD5($password.$this->getMd5($id,$password,2));
		return $this ->where(array('id'=>$id))->save(array('password'=>$password));
	}
	/**
	 * 截取手机号加密
	 * $password 输入的密码
	 * $num 判断调取手机号或者是密码
	 */
	public function getMd5($id,$password,$num){
		$password = MD5($password);
		//先查出用户数据
		$result = $this ->where(array('id'=>$id)) ->find();
		$str = substr($result['mobile'],9,11);
		if($num == 1){
		//最终的加密密码
			$password = MD5($password.$str);
			return $password;
		}else if($num == 2){
			return $str;
		}
	}
	/**
	 *找回密码的方法
	 */
	public function forgetPwd($data){
		$str = substr($data['mobile'],9,11);;
		$password = MD5($data['password']);
		$password = MD5($password.$str);
        /*查询密码是否和原来一样*/
	    $where['password'] = $password;
	    $where['mobile'] = $data['mobile'];
		$info = $this ->where($where) ->count();
		if(empty($info)){
			return $this ->where(array('mobile' =>$data['mobile'])) -> save(array('password' =>$password));
		}else{
			return false;
		}
	}	/**
	*判断是否和原来密码一样
	*/
	public function OldPwd($data){
			$str = substr($data['mobile'],9,11);;
			$password = MD5($data['password']);
		    $password = MD5($password.$str);
			/*查询密码是否和原来一样*/
			$where['password'] = $password;
			$where['mobile'] = $data['mobile'];
			$info = $this ->where($where) ->count();
		if(empty($info)){
			return false;
		}else{
			return true;
		}
	}
	/**
	 * 修改密码
	 */
	public function updatePassword($password,$spassword){
		$id = session('uid');
		$where['id'] = $id;
		$where['password'] = $password;
		$info = $this ->where($where) ->find();
		if($info){
			return $this ->where(array('id' =>$id))->save(array('password' =>$spassword));
		}else{
			return false;
		}
	}
	/**
	 * 举报
	 */
	public function jubao($id){
		$data = $this ->field('report') ->where(array('id' =>$id)) ->find();
		$report = $data['report'] + 1;
		return $this -> where(array('id' =>$id))->save(array('report' =>$report));
	}
	/**
	 *添加openid
	 */
	public function updateOpenid(){
		$id = session('uid');
		$openid = session('openid');
 		$this ->where(array('id' =>$id))->save(array('openid' =>$openid));
	}
	/*
	 *检查是否已经登录
	 */
	public function is_login($mobile){
		$where['username']  = $mobile;//lkl修正，账户登录，非Mobile
                $data['is_login'] = time();
                session('is_login',time());
		$data = $this ->field('is_login') ->where($where) ->save($data);		return $data['is_login'];
	}
	/**
	 * 更改登录状态
	 */
	public function updateLogin($key,$value){
		$where[$key]  = $value;
		$data = $this ->field('is_login') ->where($where) ->find();
         return $data['is_login'];
	}
        /***
         * 修改地区ID
         */
        public function updateArea($area_id){
            $mpa['id'] = session('uid');
            $data['area_id'] = $area_id;
            $arr = $this ->where($mpa) ->save($data);
            return $arr;
        }
        /*找省*/
        public function sheng($pid){
            $aa = D('Area')->field('pid') ->where(array('id'=>$pid)) ->find();
            $data = D('Area')->field('title') ->where(array('id' => $aa['pid'])) ->find();
            return $data;
        }
        /*查看手机*/
        public function getIsMobile($mobile){
            if($this ->where(array('mobile' =>$mobile)) ->find()){
                return "该手机号已经注册";
            }
        }
		/**
	 * 想教想学列表
	 * @param  int $teaching [教2，学1]
	 * @param  int $label    [课程标签]
	 * @param  int $sex      [性别]
	 * @param  int $age      [年龄]
	 * @param  int $identity [身份]
	 * @param  int $area_id  [地区]
	 * @param  int $star     [评价排序]
	 * @param  int $time     [发布时间排序]
	 * @param  int $salary   [最低课程价格排序]
	 * @param  str $keywords [搜索关键词]
	 * @return array         [用户列表]
	 * @author qlj
	 */
	public function teachList($teaching, $label='', $sex='', $age='',$identity='',$area_id='', $star='', $time='', $salary='', $keywords='',$limit='',$limitrow='',$num){
		//教或学
        $mainfield = 'u.id,u.nickname,u.logo,u.sex,u.age,u.area_id,u.vip_endtime';
		$map['c.teaching'] = $teaching;
		//如果是教师
		//课程须审批通过,用于构建子查询，查找课程通过审批的uid
		$map['c.passed'] = 1;
		if (!empty($label)) {
			//课程标签,用于构建子查询，查找有所选课程标签课程的uid
			$map['c.label'] = $label;
		}
		if (!empty($sex)) {
			//性别
			$where['u.sex'] = $sex;
		}
		if (!empty($age)) {
			//年龄
			if (strlen($age) == 2) {
				$where['u.age'] = array('gt', $age);
			} else if (strlen($age) == 5) {
				$where['u.age'] = array('between', $age);
			}
		}
		if (!empty($identity)) {
			//身份标识
			$where['u.identity'] = $identity;
		}
		if (!empty($area_id)) {
			//地区id
			$where['u.area_id'] = is_array($area_id) ? array('in',$area_id) : $area_id;
		}
		if (!empty($star)) {
			//按星级排序
			if ($star == 1) {
				$star = 'e.star desc';
			} else if ($star == 2) {
				$star = 'e.star';
			}
		}
		//子查询的字段
		$field = 'c.*';
		$c_order = 'c.creatE_time desc';
		if (!empty($time)) {
			//按时间排序course表
			if ($time == 1) {
				$c_order = 'c.create_time desc';
			} else if ($time == 2) {
				$c_order = 'c.create_time';
			}
			//$field = 'uid,teaching,max(create_time) as create_time,c.*';
			//构建发布时间排序条件
			//$time = 'c.' . $c_order;
		}
		if (!empty($salary)) {
            $mainfield .= ',c.salary';
			//按价格排序course表
			if ($salary == 1) {
				$c_order = 'salary asc';
			} else if ($salary == 2) {
				$c_order = 'salary desc';
			}
		}
		//关键词搜索设置
		if (!empty($keywords) && $keywords != 'c' && $keywords != 'n') {
			$str = mb_substr($keywords,-1,1,'UTF8');
			$keywords = mb_substr($keywords, 0, -1, 'UTF8');
			if ($str == 'c') {
				$map['c.title'] = array('like', "%$keywords%");
			} elseif ($str == 'n') {
				$where['u.nickname'] = array('like', "%$keywords%");
			}
		}
		$where['u.status'] = 1;
		//子查询sql语句
		//查询老师
		$where['u.end_study'] = 0;
		$uinfo = $this -> alias('u') -> field('u.*') -> join('tutor_teacher_eva as e on u.id=e.uid')->where($where)->select(false);
		if($num == 1){
			$field .=',m.id,m.nickname,m.logo,m.sex,m.age,m.area_id,m.students';
			$a = M('course') -> alias('c') -> field($field) -> join("INNER JOIN$uinfo as m on m.id = c.uid") -> where($map) -> order($c_order) ->  count();
			  return $a;
			}else{
			$field .=',m.id,m.nickname,m.logo,m.sex,m.age,m.area_id,m.students,m.lat,m.lng';
			$a = M('course') -> alias('c') -> field($field) -> join("INNER JOIN$uinfo as m on m.id = c.uid") -> where($map) -> order($c_order) -> select();
			/*数据按距离排序start yjmp*/
			$crt_lat = $_COOKIE['lat'];
			$crt_lng = $_COOKIE['lng'];
			if ($crt_lat) {
				foreach ($a as $k => $v) {
					$lat = $a[$k]['lat'];
					$lng = $a[$k]['lng'];
					$a[$k]['distance'] = $this->get_distance($crt_lat,$crt_lng,$lat,$lng);
					$a[$k]['dis_show'] = $this->get_dis_show($a[$k]['distance']);
				}
			}
			if ($star == '' && $time == '' && $salary == '') {
				$a = $this->array_sort($a, 'distance', $order=SORT_ASC);
			}
			$res = array_slice($a,$limit,$limitrow,false);
			/*数据按距离排序end yjmp*/
			return $a;
			}
	}
/*排序 yjmp*/
public function array_sort($array, $on, $order=SORT_ASC)
{
	$new_array = array();
	$sortable_array = array();  //保存key的数组
	if (count($array) > 0) {
		foreach ($array as $k => $v) {
			if (is_array($v)) {
				foreach ($v as $k2 => $v2) {
					if ($k2 == $on) {
						$sortable_array[$k] = $v2;
					}
				}
			} else {
				$sortable_array[$k] = $v;
			}
		}
		switch ($order) {
			case SORT_ASC:
				asort($sortable_array);
			break;
			case SORT_DESC:
				arsort($sortable_array);
			break;
		}
		foreach ($sortable_array as $k => $v) {
			$new_array[$k] = $array[$k];
		}
	}
	return $new_array;
}

	public function get_distance($crt_lat,$crt_lng,$lat,$lng){
		/*算距离*/
		$EARTH_RADIUS = 6370.996; // 地球半径系数
	    $PI = 3.1415926;
	    $radLat1 = $crt_lat * $PI / 180.0;
	    $radLat2 = $lat * $PI / 180.0;
	    $radLng1 = $crt_lng * $PI / 180.0;
	    $radLng2 = $lng * $PI /180.0;
	    $pa = $radLat1 - $radLat2;
	    $pb = $radLng1 - $radLng2;
	    $distance = 2 * asin(sqrt(pow(sin($pa/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($pb/2),2)));
	    $distance = round($distance * $EARTH_RADIUS,2);
	    return $distance;
	}

	public function get_dis_show($distance){
		$res = '';
		// if ($distance >= 1) {
		// 	$res = $distance."km";
		// }else{
		// 	$res = $distance*1000;
		// 	$res .= "m";
		// }
		
		$res = $distance."km";
		return $res;
	}
}